<template>
  <transition name="fade">
    <div v-if="visible" @click="handleScrollClick">
      <i class="el-icon-arrow-up" />
    </div>
  </transition>
</template>

<script>
export default {
  data() {
    return {
      el: null,
      visible: false
    }
  },
  mounted() {
    this.init()
    this.handleThrottleScroll = this._.throttle(this.handleScroll, 300)
    this.el.addEventListener('scroll', this.handleThrottleScroll)
  },
  methods: {
    init() {
      this.el = document.querySelector('header').nextSibling.children[0]
    },
    handleScrollClick() {
      let el = this.el
      let step = 0
      let interval = setInterval(() => {
        if (el.scrollTop <= 0) {
          clearInterval(interval)
          return
        }
        step += 10
        el.scrollTop -= step
      }, 20)
    },
    handleScroll() {
      const scrollTop = this.el.scrollTop
      this.visible = scrollTop >= 100
    }
  },
  beforeDestroy() {
    this.el.removeEventListener('scroll', this.handleThrottleScroll)
  }
}
</script>

<style lang="stylus" scoped>
  .fade-enter-active,
  .fade-leave-active
    transition opacity .5s
  .fade-enter,
  .fade-leave-to
    opacity 0
  div
    position fixed
    bottom 70px
    right 20px
    height 40px
    width 40px
    background-color #e9faff
    box-shadow 0 0 6px rgba(0, 0, 0, .12)
    text-align center
    line-height 40px
    color #1989fa
</style>
